﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using mshtml;
using System.IO;
using System.Net;

namespace FetchHTML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void WebBrowserDocumentCompletedEventHandler(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (textBoxLoginURL.Text.Contains(e.Url.ToString()))
            {
                WebBrowser web = (WebBrowser)sender;
                if (web.ReadyState == WebBrowserReadyState.Complete)
                {
                    HtmlDocument doc = web.Document;
                    HtmlElementCollection inputElements = web.Document.GetElementsByTagName("input");
                    if (inputElements != null)
                    {
                        foreach (HtmlElement element in inputElements)
                        {
                            if (element.GetAttribute("id").Contains("id_email"))
                            {
                                element.SetAttribute("value", textBoxLoginEmail.Text);
                                HtmlElementCollection buttonElements = web.Document.GetElementsByTagName("button");
                                if (buttonElements != null)
                                {
                                    foreach (HtmlElement button in buttonElements)
                                    {
                                        if (button.GetAttribute("value").Contains("Sign In"))
                                        {
                                            button.InvokeMember("click");
                                            break;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
            else if (e.Url.ToString().Contains(textContainString.Text))
            {
                WebBrowser web = (WebBrowser)sender;
                if (web.ReadyState == WebBrowserReadyState.Complete)
                {
                    HtmlDocument doc = web.Document;
                    HtmlElementCollection titleCollection = web.Document.GetElementsByTagName("title");
                    HtmlElementCollection bookNameCollection = web.Document.GetElementsByTagName("h1");
                    HtmlElementCollection elementCollection = web.Document.GetElementsByTagName("html");
                    string title = string.Empty;
                    string html = string.Empty;
                    string bookName = string.Empty;
                    if (titleCollection != null)
                    {
                        foreach (HtmlElement element in titleCollection)
                        {
                            title = element.InnerText;
                            title = title.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("|", "").Replace("<", "").Replace(">", "").Replace("*", "").Replace("?", "").Replace("\"", "").Replace("'", "");
                            break;
                        }
                    }
                    if (bookNameCollection != null)
                    {
                        foreach (HtmlElement element in bookNameCollection)
                        {
                            bookName = element.InnerText;
                            string[] splitNames = bookName.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            bookName = splitNames.Last();
                            break;
                        }
                    }
                    if (elementCollection != null)
                    {
                        foreach (HtmlElement element in elementCollection)
                        {
                            html = element.OuterHtml;
                            break;
                        }
                    }
                    if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(bookName) || string.IsNullOrEmpty(title))
                    {
                        return;
                    }

                    string dirPath = string.Empty;
                    if (System.IO.Directory.Exists(bookName))
                    {
                        dirPath = Path.Combine(Directory.GetCurrentDirectory(), bookName);
                    }
                    else
                    {
                        DirectoryInfo info = Directory.CreateDirectory(bookName);
                        dirPath = info.FullName;
                    }
                    // Downloading Image
                    HtmlElementCollection imgCollection = web.Document.GetElementsByTagName("img");
                    if (imgCollection != null)
                    {
                        string imgDir = Path.Combine(Directory.GetCurrentDirectory(), "images");
                        if (!Directory.Exists(imgDir))
                        {
                            Directory.CreateDirectory(imgDir);
                        }
                        foreach (HtmlElement imgElement in imgCollection)
                        {
                            string imgUrl = imgElement.GetAttribute("src");
                            if (!string.IsNullOrEmpty(imgUrl))
                            {
                                WebRequest request = WebRequest.Create(imgUrl); 
                                WebResponse response = request.GetResponse();

                                string[] imageNameTokens = imgUrl.Split('/');
                                string imageName = imageNameTokens.Last();
                                Stream reader = response.GetResponseStream();
                                string target = Path.Combine(imgDir, imageName);
                                FileStream writer = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write);
                                byte[] buff = new byte[1024];
                                int c = 0;    
                                while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                                {
                                    writer.Write(buff, 0, c);
                                }
                                writer.Close();
                                writer.Dispose();
                                reader.Close();
                                reader.Dispose();
                                response.Close();
                            }
                        }
                    }
                    

                    string outputFilePath = Path.Combine(dirPath, title + ".html");
                    File.WriteAllText(outputFilePath, html, Encoding.UTF8);
                    HtmlElementCollection spans = web.Document.GetElementsByTagName("span");
                    if (spans != null)
                    {
                        foreach (HtmlElement element in spans)
                        {
                            string attri = element.GetAttribute("classname");
                            if (attri.Contains("t-next-label"))
                            {
                                HtmlElement parent = element.Parent;
                                string href = parent.GetAttribute("href");
                                webBrowser1.Navigate(href);
                                break;
                            }
                        }
                    }
                }
            }

        }
        private void buttonOpenURL_Click(object sender, EventArgs e)
        {
            webBrowser1.DocumentCompleted += this.WebBrowserDocumentCompletedEventHandler;
            webBrowser1.Navigate(textBoxLoginURL.Text);
            webBrowser1.Visible = true;
        }

        private void buttonBeginFetch_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(textFirstPage.Text);
        }
    }
}
